const jssha = require('jssha');

// card value值拼接
function card_raw(args) {
    let values = [];
    for (var v in args) {
        values.push(args[v]);
    }
    values = values.sort();
    let string = values.join("");
    return string;
}

// JSSDK字符串格式化
function jssdk_raw(args) {
    let keys = Object.keys(args);
    keys = keys.sort();
    let newArgs = {};
    keys.forEach(function (key) {
        newArgs[key.toLowerCase()] = args[key];
    });

    let string = '';
    for (let k in newArgs) {
        string += '&' + k + '=' + newArgs[k];
    }
    string = string.substr(1);
    return string;
}

module.exports = {
    //卡券签名
    card_signature(cardId) {
        const ctx = this,
            appMkWx = ctx.app.config.app_monkeyWx,
            configMkWx = ctx.app.config.monkeyWx;

        const ret = {
            api_ticket: appMkWx.api_ticket,
            nonce_str: ctx.helper.createNonceStr(),
            timestamp: ctx.helper.createTimestamp,
            card_id: cardId || configMkWx.cardId
        };
        const string = card_raw(ret);
        const shaObj = new jssha('SHA-1', 'TEXT');
        shaObj.update(string);
        ret.signature = shaObj.getHash('HEX');

        delete ret.api_ticket;
        return ret;
    },
    //jssdk签名
    get jssdk_signature() {
        const ctx = this,
            appMkWx = ctx.app.config.app_monkeyWx,
            configMkWx = ctx.app.config.monkeyWx,
            url = configMkWx.method == 'post' ? ctx.request.body.url : ctx.query.url;

        const ret = {
            jsapi_ticket: appMkWx.jsapi_ticket,
            nonceStr: ctx.helper.createNonceStr(),
            timestamp: ctx.helper.createTimestamp,
            url: decodeURIComponent(url)
        };
        const string = jssdk_raw(ret);
        const shaObj = new jssha('SHA-1', 'TEXT');
        shaObj.update(string);
        ret.signature = shaObj.getHash('HEX');
        delete ret.jsapi_ticket;
        delete ret.url;
        ret.appId = configMkWx.appId;
        return ret;
    }
}